﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace ClojureBox
{
    public partial class Config : Form
    {
        public Config()
        {
            InitializeComponent();
        }

        public String JDKPath {
            get {
                return txtJdkHome.Text;
            }
            set {
                txtJdkHome.Text = value;
            }
        }

        private void btnConfig_Click(object sender, EventArgs e)
        {
            folderBrowserDialog1.SelectedPath = txtJdkHome.Text;

            if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
                txtJdkHome.Text = folderBrowserDialog1.SelectedPath;
        }

        private void UpdateConfFileJDKPath(string confFilePath, string confFileEntry, bool encloseWithQuote)
        {
            StreamReader sr = null;
            StringBuilder confFileStrBuilder = null;

            try
            {
                sr = File.OpenText(confFilePath);
                confFileStrBuilder = new StringBuilder();

                string enclosure = (encloseWithQuote) ? "\"" : string.Empty;
                String line = sr.ReadLine();
                while (line != null)
                {
                    if (line.StartsWith(confFileEntry))
                        confFileStrBuilder.Append(String.Format("{0}{1}{2}{1}", confFileEntry, enclosure, txtJdkHome.Text) + Environment.NewLine);
                    else
                        confFileStrBuilder.Append(line + Environment.NewLine);

                    line = sr.ReadLine();
                }
                sr.Close();

                StreamWriter sw = null;
                try
                {
                    sw = new StreamWriter(confFilePath, false);
                    sw.Write(confFileStrBuilder.ToString());
                    sw.Close();
                }
                catch (Exception ex)
                {
                    sw.Close();
                }
            }
            catch (Exception ex)
            {
                sr.Close();
            }
        }

        private void btnOk_Click(object sender, EventArgs e)
        {
            UpdateConfFileJDKPath(AppDomain.CurrentDomain.BaseDirectory + "bin\\jswat-4.4\\etc\\jswat.conf", "netbeans_jdkhome=", true);
            UpdateConfFileJDKPath(AppDomain.CurrentDomain.BaseDirectory + "bin\\WinCommand\\WinCommand.ini", "JAVA_HOME=", false);
            this.Close();
        }
    }
}
